package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.InetSocketAddress;

@Component
public class MyIpFilter implements GlobalFilter, Ordered {
    //过滤逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // ip过滤  淘宝ip 1.1.1.1
        System.out.println("MyIpFilter");

        //拿到请求和响应 为所欲为
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        InetAddress address = remoteAddress.getAddress();
        System.out.println("address:"+address);
        String hostName = remoteAddress.getHostName();
        System.out.println("hostName:"+hostName);
        String hostString = remoteAddress.getHostString();
        System.out.println("hostString:"+hostString);

        if(hostString.equals("1.1.1.1")){
            //拒绝访问
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    //过滤排序  越小越先执行
    @Override
    public int getOrder() {
        return 1;
    }
}
